<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jsp/component/common.jsp" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title></title>
    <%@include file="/WEB-INF/jsp/component/commonHead.jsp" %>
    <%@include file="/WEB-INF/jsp/component/commonBottom.jsp" %>
    <!-- bootstrapValidator验证 -->
    <link href="${assets}/bootstrapValidator/css/bootstrapValidator.css" rel="stylesheet"/>
</head>
<%--<body onresize="reSizeParentIframe()" onload="reSizeParentIframe();">--%>
<body>
<div class="row">
    <div class="col-lg-12">
        <h1 class="page-header">政府新增</h1>
    </div>
    <!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
    <form id="myForm" class="form-horizontal" method="post" >
        <input type="hidden" id="areaCode" name="areaCode" value="" />
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    政府信息
                </div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="form-group">
                                <label for="largeArea" class="col-sm-2 control-label">地区</label>
                                <div class="col-sm-3">
                                    <select id="largeArea" name="largeArea" class="form-control">
                                        <option value="">大区</option>
                                        <c:forEach items="${largeAreaList}" var="largeArea">
                                            <option value="${largeArea.largeAreaCode}">${largeArea.largeAreaName}</option>
                                        </c:forEach>
                                    </select>
                                </div>
                                <div class="col-sm-3">
                                    <select id="provinceArea" name="provinceArea" class="form-control">
                                        <option value="">省</option>
                                    </select>
                                </div>
                                <div class="col-sm-4">
                                    <select id="cityArea" name="cityArea" class="form-control">
                                        <option value="">市</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="countyArea" class="col-sm-2 control-label"></label>
                                <div class="col-sm-3">
                                    <select id="countyArea" class="form-control">
                                        <option value="">县</option>
                                    </select>
                                </div>
                                <div class="col-sm-3">
                                    <select id="townArea" class="form-control">
                                        <option value="">镇</option>
                                    </select>
                                </div>
                                <div class="col-sm-4">
                                    <select id="villageArea" class="form-control">
                                        <option value="">村</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="govName" class="col-sm-2 control-label">名称</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="govName" name="govName"
                                           placeholder="请输入名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="govAddress" class="col-sm-2 control-label">地址</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="govAddress" name="govAddress"
                                           placeholder="请输入地址">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="govType" class="col-sm-2 control-label">类别</label>
                                <div class="col-sm-10">
                                    <select id="govType" name="govType" class="form-control">
                                        <option value="1" >卫生局</option>
                                        <option value="2" >区政府</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="contracs" class="col-sm-2 control-label">联系人</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="contracs" name="contracs"
                                           placeholder="请输入联系人">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="contracsPhone" class="col-sm-2 control-label">联系人电话</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="contracsPhone" name="contracsPhone"
                                           placeholder="请输入联系人电话">
                                </div>
                            </div>
                            <div class="modal-footer" style="text-align: center ">
                                <button type="submit" class="btn btn-primary">保存</button>
                                <button type="button" class="btn btn-primary" onclick="returnMainJsp()">返回</button>
                            </div>
                        </div>
                        <!-- /.col-lg-6 (nested) -->
                    </div>
                    <!-- /.row (nested) -->
                </div>
            </div>
            <!-- /.panel -->
            <div class="panel panel-default">
                <div class="panel-heading">
                    医院信息
                </div>
                <!-- /.panel-body -->
                <div class="panel-body">
                    <div class="row">
                        <div class="col-lg-12" id="hospDiv">
                            <div class="form-group">
                                <div class="col-sm-12">
                                    <input type="button" class="btn btn-outline btn-success" id="addHospitalButt" value="添加医院" />
                                </div>
                            </div>
                        </div>
                        <!-- /.col-lg-6 (nested) -->
                    </div>
                    <!-- /.row (nested) -->
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </form>
</div>
<!-- /.row -->

<!-- 新增 -->
<div class="modal fade" id="addRelateModal">
    <div class="modal-dialog" >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
                <h4 class="modal-title">新增医院关联</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                医院名称:<input type="text" id="hospName" name="hospName"/>
                                医院等级:
                                <select id="hosp_lvl" style="width: 100px;height: 24px;">
                                    <option value="">医院等级</option>
                                    <c:forEach items="${hosp_lvl}" var="BaseDictListDate">
                                        <option value="${BaseDictListDate.code}">${BaseDictListDate.name}</option>
                                    </c:forEach>
                                </select>
                                <button id="query" class="mk_butt" >查询</button>
                            </div>
                            <!-- /.panel-heading -->
                            <div class="panel-body">
                                <div class="dataTable_wrapper">
                                    <table id="example" class="table table-striped table-bordered table-hover" width="100%">
                                        <thead>
                                        <tr align="left">
                                            <th><input id="all_id" type="checkbox" ></th>
                                            <th>医院名称</th>
                                            <th>医院等级</th>
                                            <th>医院地址</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <!-- /.panel-body -->
                        </div>
                        <!-- /.panel -->
                    </div>
                    <!-- /.col-lg-12 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="submit_add_relate">保存</button>
            </div>
        </div>
    </div>
</div>
<!-- bootstrapValidator验证 -->
<script src="${assets}/bootstrapValidator/js/bootstrapValidator.js"></script>
<!-- bootstrapValidator验证 国际化中文 -->
<script src="${assets}/bootstrapValidator/js/language/zh_CN.js"></script>

<script type="text/javascript">
    var parentWindowData= parent.top;

    //初始化table
    function initTable() {
        table = parentWindowData.$("#example").DataTable({
            "dom": "<'row'<'col-xs-2'l><'#mytool.col-xs-10'><'col-xs-6'f>r>" +
            "t" +
            "<'row'<'col-xs-6'i><'col-xs-6'p>>",
            "bFilter": false,//去掉搜索框
            "bAutoWidth": true, //自适应宽度
            "sPaginationType" : "full_numbers",
            "lengthMenu": [[5, 10], [5, 10]],
            "ordering": false,//是否允许Datatables开启排序
            "bProcessing" : true,
            "bServerSide" : true,
            "sAjaxSource" : "${URL_ADM_HOSP_SEARCHALL}",
            "sAjaxDataProp": "dataList",//查询后，返回的集合
            "fnServerData": function ( sSource, aoData, fnCallback ) {  //查询条件
                aoData.push(
                        { "name": "hospName", "value": parentWindowData.$("#hospName").val() }
                );
                aoData.push(
                        { "name": "hosLevel", "value": parentWindowData.$("#hosp_lvl").val() }
                );
                $.ajax( {
                    "dataType": 'json',
                    "url": sSource,
                    "type":'post',
                    "data": aoData,
                    "success": fnCallback,
                    "complete":function(data){
                        parentWindowData.$("#dialog-Show #all_id").prop("checked","");
                        parentWindowData.$("#dialog-Show input[name='id']").each(function () {
                            var rowData=table.row($(this).parents('tr') ).data();

                            if($("#hospDiv input[value=\'"+rowData.id+"\']").length>0){
                                $(this).prop("checked","checked");
                                $(this).parents("tr").toggleClass('active');
                            }
                        });
                    }
                } );

            },
            "aoColumns" : [ {
                "targets": -1,
                "data": null,
                "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $(nTd).html('' +
                            '&nbsp;&nbsp;<input name="id" value="'+oData.id+'" type="checkbox">' +
                            '');
                }
            }, {
                "mDataProp" : "hospName",
                'sClass': "text-center"
            }, {
                "mDataProp" : "hosLevelString",
                "sDefaultContent" : ""
            }, {
                "mDataProp" : "hospAddress"
            }
            ],
            "oLanguage" : {
                "sProcessing" : "正在加载中......",
                "sLengthMenu" : "每页显示 _MENU_ 条记录",
                "sZeroRecords" : "没有数据！",
                "sEmptyTable" : "无数据存在！",
                "sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
                "sInfoEmpty" : "显示0到0条记录",
                "sInfoFiltered" : "数据表中共为 _MAX_ 条记录",
                //"sSearch" : "搜索",
                "oPaginate" : {
                    "sFirst" : "首页",
                    "sPrevious" : "上一页",
                    "sNext" : "下一页",
                    "sLast" : "末页"
                }
            },
            initComplete: function () {

                parentWindowData.$('#dialog-Show tbody ').on("click","tr" ,function () {
                    $(this).toggleClass('active');
                    if($(this).hasClass('active')){
                        $(this).children('td').children("input").prop("checked","checked");
                    }else{
                        $(this).children('td').children("input").prop("checked","");
                    }
                });
            }
        });
    }

    //返回上一页
    function returnMainJsp(){
        window.location.href='${URL_ADM_GOVERNMENT_TOSEARCH}';
    }

    $(function () {
        $("#largeArea").change(function() {
            if(this.value==null || this.value==""){
                resetArea(0);
            }else{
                getLowerAreaList("provinceArea",this.value,0);
                resetArea(1);
            }
        });
        $("#provinceArea").change(function() {
            if(this.value==null || this.value==""){
                resetArea(1);
            }else{
                getLowerAreaList("cityArea",this.value,1);
                resetArea(2);
            }
        });
        $("#cityArea").change(function() {
            if(this.value==null || this.value==""){
                resetArea(2);
            }else{
                getLowerAreaList("countyArea",this.value,2);
                resetArea(3);
            }
        });
        $("#countyArea").change(function() {
            if(this.value==null || this.value==""){
                resetArea(3);
            }else{
                getLowerAreaList("townArea",this.value,3);
                resetArea(4);
            }
        });
        $("#townArea").change(function() {
            if(this.value==null || this.value==""){
                resetArea(4);
            }else{
                getLowerAreaList("villageArea",this.value,4);
                resetArea(5);
            }
        });

        /**
         * 后台获取下级列表
         * */
        function getLowerAreaList(id,code,level){
            $.ajax({
                url:'${ctx}/area/getLowerAreaList',
                type:'post',
                data:'code='+code+"&level="+level,
                async : false, //默认为true 异步
                error:function(){
                    alert('error');
                },
                success:function(data){
                    var objs = document.getElementById(id);
                    objs.options.length = 1;
                    var area = data;
                    for(var i=0;i<area.length;i++){
                        var childOption = document.createElement("option");
                        childOption.value = area[i].code;
                        childOption.innerHTML = area[i].name;
                        objs.appendChild(childOption);
                    }
                }
            });
        }

        /**
         * 重置下级菜单
         * */
        function resetArea(level){
            if(level<1){
                var provinceArea = document.getElementById("provinceArea");
                provinceArea.options.length = 1;
            }
            if(level<2){
                var cityArea = document.getElementById("cityArea");
                cityArea.options.length = 1;
            }
            if(level<3){
                var countyArea = document.getElementById("countyArea");
                countyArea.options.length = 1;
            }
            if(level<4){
                var townArea = document.getElementById("townArea");
                townArea.options.length = 1;
            }
            if(level<5){
                var villageArea = document.getElementById("villageArea");
                villageArea.options.length = 1;
            }
        }

        /**
         * 获取最详细地址code
         * */
        function getDetailAreaCode(){
            var villageArea = $("#villageArea").val();//村code
            var townArea = $("#townArea").val();//镇code
            var countyArea = $("#countyArea").val();//县code
            var cityArea = $("#cityArea").val();//市code
            var provinceArea = $("#provinceArea").val();//省code
            var largeArea = $("#largeArea").val();//大区code
            if(villageArea!=null && villageArea!=""){
                return villageArea;
            }else if(townArea!=null && townArea!=""){
                return townArea;
            }else if(countyArea!=null && countyArea!=""){
                return countyArea;
            }else if(cityArea!=null && cityArea!=""){
                return cityArea;
            }else if(provinceArea!=null && provinceArea!=""){
                return provinceArea;
            }else if(largeArea!=null && largeArea!=""){
                return largeArea;
            }else{
                return "";
            }
        }

        /**
         * 添加医院弹出框
         * */
        $("#addHospitalButt").click(function(){
            parentWindowData.$("#dialog-Show").html($('#addRelateModal').html());
            initTable();
            parentWindowData.$("#dialog-Show").modal({ show: true, backdrop: 'static' });

            var width = 800;
            var height = 800;
            var mycss={"width":width+"px","height":height+"px","top":(($(window).height()-height)/2>0?($(window).height()-height)/2:0)+"px"};
            parentWindowData.$('#dialog-Show .modal-dialog').css(mycss).find('.modal-content').css({height: '100%',width: '100%'}).find('.modal-body').css({height: '80%' });
            parentWindowData.$("#dialog-Show #submit_add_relate").click(function(){
                addRelate();
            })
            parentWindowData.$("#dialog-Show #all_id").click(function(){
                isCheckedAll('dialog-Show');
            })
            parentWindowData.$("#dialog-Show #query").click(function(){
                table.ajax.reload();
            })
        });

        function isCheckedAll(TableIdData) {
            var decSelectAll = false;
            if (parentWindowData.$("#" + TableIdData + " thead input").prop("checked")) {
                decSelectAll = true;
            }

            parentWindowData.$("#" + TableIdData + " tbody tr").each(function () {
                if ($(this).hasClass('active') && !decSelectAll) {
                    $(this).toggleClass('active');
                    $(this).children('td').children("input").prop("checked", "");
                } else if (!$(this).hasClass('active') && decSelectAll) {
                    $(this).toggleClass('active');
                    $(this).children('td').children("input").prop("checked", "checked");
                }
            });
        }

        function addRelate(){
            parentWindowData.$("#dialog-Show input[name='id']").each(function () {
                var rowData=table.row($(this).parents('tr') ).data();
                if (this.checked) {
                    if($("#hospDiv input[value=\'"+rowData.id+"\']").length==0) {
                        addHospDiv(rowData.id, rowData.hospName, rowData.hosLevelString, rowData.hospAddress);
                    }
                    return;
                }
                $("#hospDiv input[value=\'"+rowData.id+"\']").parent().remove();
            });
            parentWindowData.$('#dialog-Show').modal('hide');
        }

        /**
         * 医院弹出框确定按钮
         * */
        $("#submit_add_relate").click(function(){
            document.getElementById('addRelateIframe').contentWindow.addRelate();
        });

        $('#myForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                largeArea: {
                    validators: {
                        notEmpty: true
                    }
                },
                provinceArea: {
                    validators: {
                        notEmpty: true
                    }
                },
                cityArea: {
                    validators: {
                        notEmpty: true
                    }
                },
                govName: {
                    validators: {
                        notEmpty: true
                    }
                }
            }
        }).on('success.form.bv', function (e) {
            e.preventDefault();
            $("#areaCode").val(getDetailAreaCode());
            $.ajax({
                url:'${URL_ADM_GOVERNMENT_ADD}',
                type:'post',
                data:$('#myForm').serialize(),
                async : false, //默认为true 异步
                error:function(){
                    alert('error');
                },
                success:function(data){
                    window.location.href='${URL_ADM_GOVERNMENT_TOSEARCH}';
                }
            });
        });

    });

    /**
     * 在当前页面添加医院信息
     * */
    function addHospDiv(id,hospName,levelName,hospAddress){
        var hospHtml = ""
                + '<div class="form-group">'
                + '<input type="hidden" name="hospId" value="'+id+'"/>'
                + '<label class="col-sm-3">'+hospName+'</label>'
                + '<label class="col-sm-2">'+levelName+'</label>'
                + '<label class="col-sm-6">'+hospAddress+'</label>'
                + '<div class="col-sm-1"><input type="button" class="btn btn-outline btn-success" value="删除" onclick="removeHosp(this)" /></div>'
                + '</div>';
        $("#hospDiv").append(hospHtml);
    }

    /**
     * 删除当前行（医院信息）
     * */
    function removeHosp(removeButt){
        $(removeButt).parent().parent().remove();
    }

</script>
</body>
</html>